package cn.zwxky.android.user.Search;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.Event.LsfbEvent;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.utils.valid.Valid;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.zwxky.android.user.R;
import cn.zwxky.android.user.Utils.LittleUtils;
import cn.zwxky.android.user.Utils.NoDoubleClickUtils;
import cn.zwxky.android.user.Utils.URLString;
import cn.zwxky.android.user.Utils.myProgressDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * 文件选择器页面
 * Created by Administrator on 2017/2/14 0014.
 */
@ContentView(R.layout.aty_file_uploading)
public class FileUploadingActivity extends LsfbActivity {

    @ViewInject(R.id.dish_list)
    private RecyclerView dish_list;

    private myProgressDialog dialog;

    /**
     * RecyclerView的布局管理器
     */
    private RecyclerView.LayoutManager mlayoutManager;

    /**
     * 适配器
     */
    private FileUploadingAdapter adapter;

    /**
     * 用于存放获取到的数据
     */
    private List<FileUploadingBean> datas;

    private FileUploadingBean bean;

    private int code = 0;

    private String data="";


    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);

            switch (msg.what) {
                case 1000:
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    public void initView() {

        //去掉信息栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        LittleUtils.setsimpletitlebar(this, "文件选择");
        TextView textView = new TextView(this);
        textView.setText("上传");
        textView.setTextColor(Color.WHITE);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    upload();
                }

            }
        });
        getTitleBar().setRightView(textView, 0, 0, DensityUtils.dp2px(this, 16), 0);

        dialog = new myProgressDialog(this, "上传中，请等待...");
        datas = new ArrayList<>();
        adapter = new FileUploadingAdapter(this, datas, R.layout.item_file_uploading);
        mlayoutManager = new LinearLayoutManager(this);//布局模式为listview方式
        dish_list.setLayoutManager(mlayoutManager);
        dish_list.setAdapter(adapter);

    }

    @Override
    public void initEvent() {

    }

    @Override
    public void initData() {
//        getSpecificTypeOfFile(this, new String[]{".docx", ".doc", ".xls", ".xlsx", ".pdf", ".jpg", ".png", ".zip", ".rar"});
        getSpecificTypeOfFile(this, new String[]{".docx", ".doc", ".xls", ".xlsx", ".pdf", ".zip", ".rar"});
    }

    public void getSpecificTypeOfFile(Context context, String[] extension) {
        //从外存中获取
        Uri fileUri = MediaStore.Files.getContentUri("external");
        //筛选列，这里只筛选了：文件路径和不含后缀的文件名
        String[] projection = new String[]{
                MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.TITLE
        };
        //构造筛选语句
        String selection = "";
        for (int i = 0; i < extension.length; i++) {
            if (i != 0) {
                selection = selection + " OR ";
            }
            selection = selection + MediaStore.Files.FileColumns.DATA + " LIKE '%" + extension[i] + "'";
        }
        //按时间递增顺序对结果进行排序;待会从后往前移动游标就可实现时间递减
        String sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED;
        //获取内容解析器对象
        ContentResolver resolver = context.getContentResolver();
        //获取游标
        Cursor cursor = resolver.query(fileUri, projection, selection, null, sortOrder);
        if (cursor == null)
            return;
        //游标从最后开始往前递减，以此实现时间递减顺序（最近访问的文件，优先显示）
        if (cursor.moveToLast()) {
            do {
                //输出文件的完整路径
                String data = cursor.getString(0);
                bean = new FileUploadingBean();
                bean.setName(data);
                bean.setNumber(String.valueOf(code));
                datas.add(code, bean);
                code++;
                adapter.notifyDataSetChanged();
                Log.e("tag", data);
            } while (cursor.moveToPrevious());
        }
        cursor.close();
    }


    @EventAnnotation
    public void FileClickEvent(FileClickEvent event) {
        for (FileUploadingBean dataBean : datas) {
            dataBean.check = false;
            if (dataBean.getNumber() == event.getData()) {
                dataBean.check = true;
                data = dataBean.getName();
            }
        }
        handler.sendEmptyMessage(1000);
    }

    public void upload() {

        if (data.isEmpty()){
            SN.SnackShow(dish_list,"请选择文件");
            return;
        }

        dialog.showdialog();
        File file = new File(data);
        HttpClient client = new HttpClient();
        List<File> fileList = new ArrayList<File>();
        fileList.add(file);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("uid", Config.getUserId());
        hashMap.put("img", data);

        client.postFile(URLString.UPLOAD + LittleUtils.getToken(URLString.UPLOAD), hashMap, fileList, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                dialog.hidedialog();
                LsfbLog.e("上传错误");
//                T.showShort(FileUploadingActivity.this,"上传错误,请稍后再试");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                dialog.hidedialog();
                LsfbLog.e("上传成功");

                String reAddress = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(reAddress);
                    JSONObject img = jsonObject.getJSONObject("data");
                    String file_name = img.getString("img");

                    FilebackEvent event = new FilebackEvent();
                    event.setData(file_name);
                    LsfbEvent.getInstantiation().post(event);

                    FilebackEvent2 event2 = new FilebackEvent2();
                    event2.setData(data);
                    LsfbEvent.getInstantiation().post(event2);
//                    T.showShort(FileUploadingActivity.this,"上传成功");
                    finish();

                } catch (JSONException e) {
                    LsfbLog.e(Log.getStackTraceString(e));
                    e.printStackTrace();
                }

            }
        });
    }

}
